package com.xgy.userauthsystem.controller;

import com.xgy.userauthsystem.dto.*;
import com.xgy.userauthsystem.entity.User;
import com.xgy.userauthsystem.exception.*;
import com.xgy.userauthsystem.service.UserService;
import jakarta.validation.Valid;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

/**
 * 用户认证控制器
 * 处理用户注册和登录请求
 */
@RestController
@RequestMapping("/api/auth")
public class UserController {

    private static final Logger logger = LoggerFactory.getLogger(UserController.class);// 创建日志记录器

    private final UserService userService;// 声明用户服务变量

    // 构造函数，自动注入用户服务
    @Autowired
    public UserController(UserService userService) {
        this.userService = userService;
    }

    /**
     * 用户注册接口
     * 接收用户注册请求，包含用户名、密码、邮箱和验证码
     * @param authRequest 注册请求
     * @return 注册结果
     */
    @PostMapping("/register")
    public ResponseEntity<ApiResponse<User>> register(@Valid @RequestBody AuthRequest authRequest) {
        logger.info("接收到注册请求: {}", authRequest.getUsername());

        try {
            // 创建用户对象
            User user = new User(
                    authRequest.getUsername(),
                    authRequest.getPassword(),
                    authRequest.getEmail()
            );

            // 调用服务层进行注册（包含验证码验证）
            User registeredUser = userService.register(
                    user, 
                    authRequest.getCaptchaId(), 
                    authRequest.getCaptcha()
            );

            logger.info("用户注册成功: {}", registeredUser.getUsername());
            return ResponseEntity.ok(
                    ApiResponse.success("注册成功", registeredUser)
            );

        } catch (UsernameAlreadyExistsException | InvalidPasswordException | InvalidCaptchaException | EmailAlreadyExistsException e) {
            // 这些异常我们期望在业务逻辑中发生，由全局异常处理器处理
            logger.warn("注册失败: {}", e.getMessage());
            throw e;
        } catch (Exception e) {
            // 其他未预期的异常
            logger.error("注册过程中发生未知错误", e);
            return ResponseEntity.badRequest().body(
                    ApiResponse.error("注册失败: " + e.getMessage(), "REGISTER_ERROR")
            );
        }
    }

    /**
     * 用户登录接口
     * 接收用户登录请求，包含用户名和密码
     * @param loginRequest 登录请求
     * @return 登录结果
     */
    @PostMapping("/login")
    public ResponseEntity<ApiResponse<User>> login(@Valid @RequestBody LoginRequest loginRequest) {
        logger.info("接收到登录请求: {}", loginRequest.getUsername());

        try {
            // 调用服务层进行登录验证
            User user = userService.login(
                    loginRequest.getUsername(),
                    loginRequest.getPassword()
            );

            logger.info("用户登录成功: {}", user.getUsername());
            return ResponseEntity.ok(
                    ApiResponse.success("登录成功", user)
            );

        } catch (InvalidLoginException e) {
            // 登录失败的预期异常，由全局异常处理器处理
            logger.warn("登录失败: {}", e.getMessage());
            throw e;
        } catch (Exception e) {
            // 其他未预期的异常
            logger.error("登录过程中发生未知错误", e);
            return ResponseEntity.badRequest().body(
                    ApiResponse.error("登录失败: " + e.getMessage(), "LOGIN_ERROR")
            );
        }
    }

    /**
     * 发送邮箱验证码接口
     * 接收发送邮箱验证码请求，包含邮箱地址
     * @param request 发送验证码请求
     * @return 发送结果
     */
    @PostMapping("/send-email-code")
    public ResponseEntity<ApiResponse<String>> sendEmailCode(@Valid @RequestBody SendEmailCodeRequest request) {
        logger.info("接收到发送邮箱验证码请求: {}", request.getEmail());

        try {
            // 调用服务层发送验证码
            userService.sendEmailCode(request.getEmail());

            logger.info("邮箱验证码发送成功: {}", request.getEmail());
            return ResponseEntity.ok(
                    ApiResponse.success("验证码发送成功，请查看邮箱")
            );

        } catch (EmailNotFoundException e) {
            logger.warn("邮箱不存在: {}", request.getEmail());
            throw e;
        } catch (Exception e) {
            logger.error("发送邮箱验证码过程中发生未知错误", e);
            return ResponseEntity.badRequest().body(
                    ApiResponse.error("验证码发送失败: " + e.getMessage(), "SEND_CODE_ERROR")
            );
        }
    }

    /**
     * 邮箱验证码登录接口
     *
     * @param request 邮箱登录请求
     * @return 登录结果
     */
    @PostMapping("/email-login")
    public ResponseEntity<ApiResponse<User>> emailLogin(@Valid @RequestBody EmailLoginRequest request) {
        logger.info("接收到邮箱验证码登录请求: {}", request.getEmail());

        try {
            // 调用服务层进行邮箱验证码登录验证
            User user = userService.emailLogin(
                    request.getEmail(),
                    request.getCode()
            );

            logger.info("用户邮箱验证码登录成功: {}", user.getEmail());
            return ResponseEntity.ok(
                    ApiResponse.success("登录成功", user)
            );

        } catch (EmailNotFoundException | EmailCodeExpiredException | EmailCodeIncorrectException e) {
            logger.warn("邮箱验证码登录失败: {}", e.getMessage());
            throw e;
        } catch (Exception e) {
            logger.error("邮箱验证码登录过程中发生未知错误", e);
            return ResponseEntity.badRequest().body(
                    ApiResponse.error("登录失败: " + e.getMessage(), "EMAIL_LOGIN_ERROR")
            );
        }
    }

    /**
     * 健康检查接口
     * @return 服务状态
     */
    @GetMapping("/health")
    public ResponseEntity<ApiResponse<String>> healthCheck() {
        return ResponseEntity.ok(
                ApiResponse.success("用户认证服务运行正常")
        );
    }
}